package com.wey.handler.ExceotionHandler;

import com.wey.R;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Set;

@RestControllerAdvice
public class GlobalExceptionHandler  {
    @ExceptionHandler(MyException.class)
    public R MyException(MyException ex) {
        return R.error(ex.getMessage());
    }
    //参数校验异常
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R methodArgumentNotValidException(MethodArgumentNotValidException e){
        e.printStackTrace();
        //拿到错误
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        StringBuilder sb = new StringBuilder();
        allErrors.forEach(error->{
            //拿到错误信息，拼接
            sb.append(error.getDefaultMessage()).append(" ; ");
        });
        return R.error(sb.toString());
    }

//    @ExceptionHandler(value = MissingServletRequestParameterException.class)
//    public R methodArgumentNotValidException(MissingServletRequestParameterException e){
//        e.printStackTrace();
//        return R.error(e.getMessage());
//    }
//
//    @ExceptionHandler(value = ConstraintViolationException.class)
//    public R constraintViolationException(ConstraintViolationException e) {
//        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
//        StringBuilder sb = new StringBuilder();
//        for (ConstraintViolation<?> violation : violations) {
//            sb.append(violation.getMessage()).append(";");
//        }
//        return R.error(sb.toString());
//    }

    //捕获其他未知异常
    @ExceptionHandler(value = Exception.class)
    public R exceptionHandler(Exception e){
        e.printStackTrace();
        return R.error(e.getMessage());
    }
}
